<template>
  <div class="city-search">
    <el-autocomplete
      v-model="searchValue"
      :fetch-suggestions="handleSearch"
      :debounce="300"
      :loading="loading"
      placeholder="请输入城市名称"
      clearable
      @select="handleSelect"
      @keyup.enter="handleEnter"
      class="search-input"
    >
      <template #default="{ item }">
        <div class="suggestion-item">
          <el-icon><el-icon-location /></el-icon>
          <span class="city-name">{{ item.name }}</span>
          <span class="country-code">{{ item.country }}</span>
        </div>
      </template>
      
      <template #prepend>
        <el-icon><el-icon-search /></el-icon>
      </template>
      
      <template #append>
        <el-button 
          type="primary" 
          @click="handleEnter"
          :loading="loading"
          :disabled="!searchValue"
        >
          查询
        </el-button>
      </template>
    </el-autocomplete>
    
    <!-- 搜索历史 -->
    <div v-if="showHistory && searchHistory.length > 0" class="search-history">
      <div class="history-header">
        <span>搜索历史</span>
        <el-button link size="small" @click="clearHistory">清空</el-button>
      </div>
      
      <div class="history-tags">
        <el-tag
          v-for="city in searchHistory"
          :key="city"
          closable
          @click="selectCity(city)"
          @close="removeFromHistory(city)"
          class="history-tag"
        >
          {{ city }}
        </el-tag>
      </div>
    </div>
    
    <!-- 热门城市 -->
    <div v-if="showHotCities" class="hot-cities">
      <div class="hot-header">热门城市</div>
      
      <div class="hot-tags">
        <el-tag
          v-for="city in hotCities"
          :key="city"
          @click="selectCity(city)"
          class="hot-tag"
        >
          {{ city }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { 
  ElAutocomplete, 
  ElButton, 
  ElIcon, 
  ElTag,
  ElMessage
} from 'element-plus'
import { 
  Search as ElIconSearch,
  Location as ElIconLocation
} from '@element-plus/icons-vue'
import { useWeatherStore } from '@/stores/weather'
import type { City } from '@/types'

// Props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  loading: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: string]
  'search': [city: string]
}>()

// Store
const weatherStore = useWeatherStore()

// 内部状态
const searchValue = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 计算属性
const searchHistory = computed(() => weatherStore.searchHistory)
const showHistory = computed(() => !searchValue.value && searchHistory.value.length > 0)
const showHotCities = computed(() => !searchValue.value && searchHistory.value.length === 0)

// 热门城市
const hotCities = [
  '北京',
  '上海',
  '广州',
  '深圳',
  '成都',
  '杭州',
  '武汉',
  '西安',
  '重庆',
  '南京'
]

// 搜索建议
interface SuggestionItem {
  value: string
  name: string
  country: string
  lat: number
  lon: number
}

// 处理搜索
const handleSearch = async (queryString: string, cb: (suggestions: SuggestionItem[]) => void) => {
  if (!queryString) {
    // 显示搜索历史
    const historySuggestions = searchHistory.value.map(city => ({
      value: city,
      name: city,
      country: 'CN',
      lat: 0,
      lon: 0
    }))
    cb(historySuggestions)
    return
  }
  
  try {
    const cities = await weatherStore.searchCities(queryString)
    const suggestions: SuggestionItem[] = cities.map(city => ({
      value: city.name,
      name: city.name,
      country: city.country,
      lat: city.lat,
      lon: city.lon
    }))
    cb(suggestions)
  } catch (error) {
    console.error('搜索城市失败:', error)
    cb([])
  }
}

// 选择建议项
const handleSelect = (item: SuggestionItem) => {
  searchValue.value = item.value
  emit('search', item.value)
}

// 回车搜索
const handleEnter = () => {
  if (searchValue.value) {
    emit('search', searchValue.value)
  }
}

// 选择城市
const selectCity = (city: string) => {
  searchValue.value = city
  emit('search', city)
}

// 清空历史
const clearHistory = () => {
  localStorage.removeItem('weatherSearchHistory')
  weatherStore.searchHistory = []
  ElMessage.success('搜索历史已清空')
}

// 从历史中移除
const removeFromHistory = (city: string) => {
  const index = weatherStore.searchHistory.indexOf(city)
  if (index > -1) {
    weatherStore.searchHistory.splice(index, 1)
    localStorage.setItem('weatherSearchHistory', JSON.stringify(weatherStore.searchHistory))
  }
}
</script>

<style lang="scss" scoped>
.city-search {
  .search-input {
    width: 100%;
    
    :deep(.el-input__wrapper) {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      
      &:hover {
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.12);
      }
    }
  }
  
  .suggestion-item {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 0;
    
    .el-icon {
      color: var(--el-color-primary);
    }
    
    .city-name {
      flex: 1;
      font-weight: 500;
    }
    
    .country-code {
      font-size: 12px;
      color: var(--el-text-color-secondary);
      background: var(--el-fill-color-light);
      padding: 2px 6px;
      border-radius: 2px;
    }
  }
  
  .search-history,
  .hot-cities {
    margin-top: 16px;
    padding: 16px;
    background: var(--el-fill-color-light);
    border-radius: 8px;
  }
  
  .history-header,
  .hot-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
    font-size: 14px;
    color: var(--el-text-color-regular);
  }
  
  .history-tags,
  .hot-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    .history-tag,
    .hot-tag {
      cursor: pointer;
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

// 深色模式适配
.dark {
  .city-search {
    .search-history,
    .hot-cities {
      background: var(--el-bg-color-page);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .city-search {
    .search-input {
      :deep(.el-input-group__append) {
        .el-button {
          padding: 0 12px;
        }
      }
    }
  }
}
</style> 